package com.kinon.ceshiaccount.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.kinon.ceshiaccount.R;

/**
 * Created by luohao on 2017-07-24.
 */

public class KeyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //    private ArrayList<>
    private String list[];
    private Context context;

    private OnRecyclerClickListener listener = null;

    public KeyAdapter(String[] list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getItemCount() {
        return list.length;
    }

    //创建childview
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate
                (R.layout.item_key_layout, parent, false);
        MyHolder holder = new MyHolder(view, listener);
        return holder;
    }

    //绑定数据
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        // instanceof 二元操作符 判断左边的类是否是右边的类
        if (holder instanceof MyHolder) {
            ((MyHolder) holder).btn.setText(list[position]);
        }
    }

    public void setOnItemClickListener(OnRecyclerClickListener listener) {
        this.listener = listener;
    }

    public static interface OnRecyclerClickListener {
        void onItemClick(View view, int position);
    }

    private class MyHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        private Button btn;
        private OnRecyclerClickListener mlistener = null;

        public MyHolder(View itemView, OnRecyclerClickListener listener) {
            super(itemView);
            btn = (Button) itemView.findViewById(R.id.btn_key);
            this.mlistener = listener;
            btn.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mlistener != null) {
                mlistener.onItemClick(view, getPosition());
            }
        }
    }

}
